package cn.gzzhome.utils

/**
 * 参数管理者
 */
class CommandParamManager {

    Map<String, CommandParam> paramMap = [:] as LinkedHashMap

    Map<String, List> defaultValues = [:]

    CommandParamManager(Map<String, Closure> params) {
        params.each {
            paramMap[it.key] = new CommandParam(it.key, it.value)
        }
    }

    CommandParamManager(List<List> params) {
        params.each {
            paramMap["${it[0]}".toString()] = it as CommandParam
        }
    }

    def help() {
        println("参数列表：")
        def sb = ""
        def nameLen = paramMap.keySet().max({ it.length() }).length()
        def blank = ""
        (0..nameLen - 1).toList().each { blank += " " }
        blank += "\t"
        paramMap.each({
            sb += "${it.key}${blank.substring(it.key.length())}${it.value.description}\n"
        })
        println(sb)
    }

    /**
     * 构建参数
     * @param cb
     * @return
     */
    def build(Closure cb) {
        if(cb){
            cb.delegate = paramMap
            cb()
        }
        def sb = ""
        paramMap.each {
            String key = it.key
            CommandParam param = it.value
            try {
                if (!param.values && defaultValues.containsKey(key)) {
                    param.values += defaultValues[key]
                }
                def cmd = param.build()
                if (cmd) {
                    sb += " ${cmd}"
                }
            } catch (Exception e) {
                println "参数${param.name ? param.name : key}构建失败：${e.getMessage()}"
                throw new RuntimeException(e)
            }
        }
        return sb.trim()
    }

    /**
     * 构建命令
     * @param cmd
     * @param cb
     * @return
     */
    def build(String cmd, Closure cb) {
        return "${cmd} ${build(cb)}"
    }

    /**
     * 添加默认值
     * @param key
     * @param values
     * @return
     */
    def addDefault(String key, List values) {
        if (!defaultValues.containsKey(key)) {
            defaultValues[key] = []
        }
        defaultValues[key] += values
    }

    /**
     * 获取某个参数的值
     * @param key
     * @return
     */
    def getParamValues(String key) {
        if (paramMap.containsKey(key)) {
            CommandParam param = paramMap.get(key)
            return param.values
        } else {
            throw new RuntimeException("未知参数：${key}")
        }
    }

}
